<?php
namespace app\job;
use think\queue\Job;
use think\Db;
use think\Controller;
class Job1 extends Controller
{
    public function fire(Job $job, $data)
    {
        //....这里执行具体的任务
        $data = json_decode($data,true);
        if($this->jobDone($data))
        {
            $job->delete();
            print("<info>Hello Job has been done and deleted"."</info>\n");
        }else{
            $job->release(3); //$delay为延迟时间
            print("<info>mmmmmmmmmmmmmmmmmmmmm"."</info>\n");
        }
//        if ($job->attempts() > 3) {
//            //通过这个方法可以检查这个任务已经重试了几次了
//        }
        //如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
        // $job->delete();
        // 也可以重新发布这个任务
        // $job->release($delay); //$delay为延迟时间
    }
    public function failed($data)
    {
        // ...任务达到最大重试次数后，失败了
    }
    //pa
    public function jobDone($titles)
    {
                $datatitle = $titles['title'];
        //查询数据库
        $data = array(
            'question'=> $datatitle,
        );

        $query = http_build_query($data);

        $options['http'] = array(
            'timeout'=>60,
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $query
        );
        $context = stream_context_create($options);
        $result = file_get_contents('http://www.quchap.cn',false, $context);

        $pattern = '/题目:(.*?)<\/p>/i';
        preg_match($pattern, $result, $matches);

        $pattern = '/答案:(.*?)<\/p>/i';
        preg_match($pattern, $result, $matches2);
        if($matches&&$matches2){
            $title=$matches[1];
            $answer=$matches2[1];
            $data = [
                'title'		=> $title,
                'answer'	=> $answer
            ];
            $result = Db::name("pachong")->insert($data);
            if($result){
                Db::name("datatablelog")->where(['id' => $titles['id']])->delete();
                return true;
            }else{
                Db::name("datatablelog")->where(['id' => $titles['id']])->update(['status' => 2]);
                return true;
            }
        }else{
            Db::name("datatablelog")->where(['id' => $titles['id']])->update(['status' => 1]);
            return true;
        }
    }


}
